package com.dzl.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.caucho.hessian.client.HessianProxyFactory;
import com.dzl.aliyunoss.ALiYunOSSConstant;
import com.dzl.constant.UploadConstant;
import com.yome.upload.service.FileUploadService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 图片上传工具类
 * @author liufan
 *
 */
public class UploadUtil {

	/**
	 * 上传Logo图片
	 */
	public static Map<String, Object> uploadImg(HttpServletRequest request,String type,String ispic) {
		Map<String,Object> map = new HashMap<String,Object>();
		String message = "";
		String imagepath = "";
		String imageType = type;
		boolean success = true;
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(request);
			//resultJson = uploadApi.uploadImg(type, ispic, items);
			//是否是上传图片
			boolean isPic = ImageUtils.toBoolean(ispic, true);
			if (UploadConstant.IMAGE_TYPE_COMPANY.equals(imageType)) {//企业
				imagepath = UploadConstant.IMAGE_URL_COMPANY;
			}else if(UploadConstant.IMAGE_TYPE_ORDER.equals(imageType)){//订单
				imagepath = UploadConstant.IMAGE_URL_ORDER;
			}else if(UploadConstant.IMAGE_TYPE_STYLE.equals(imageType)){//款式
				imagepath = UploadConstant.IMAGE_URL_STYLE;
			}else if(UploadConstant.IMAGE_TYPE_CATE.equals(imageType)){//分类
				imagepath = UploadConstant.IMAGE_URL_CATE;
			}else if(UploadConstant.IMAGE_TYPE_DRIVING.equals(imageType)){//驾照
				imagepath = UploadConstant.IMAGE_URL_DRIVING;
			}else if(UploadConstant.IMAGE_TYPE_PROOF.equals(imageType)){//驾照
				imagepath = UploadConstant.IMAGE_URL_PROOF;
			}else if(UploadConstant.IMAGE_TYPE_STYLE_ZILIAO.equals(imageType)){//款式资料
				imagepath = UploadConstant.IMAGE_URL_STYLE;
			}else if(UploadConstant.IMAGE_TYPE_IDENTIFICATION_CARD.equals(imageType)){//身份证
				imagepath = UploadConstant.IMAGE_URL_IDENTIFICATION_CARD;
			}else if(UploadConstant.IMAGE_TYPE_BACK_SMALL_APP.equals(imageType)){//小程序背景图
				imagepath = UploadConstant.IMAGE_URL_BACK_SMALL_APP;
			}else{//其他
				imagepath = UploadConstant.IMAGE_URL_OTHER;
			}

			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField())
					continue;
				else {
					if (!EmptyUtils.isEmpty(item.getName())) {

						/* 获取文件上传路径名称 */
						String fileNameLong = item.getName();

						File tempFile = new File(fileNameLong);// ie浏览器会把本地地址传递过来

						if (tempFile.isFile()) {
							fileNameLong = tempFile.getName();
						}

						/* 获取文件扩展名 */
						String ext = fileNameLong.substring(fileNameLong.lastIndexOf(".") + 1);
						long imageSize = item.getSize();
						if (imageSize == 0) {
							success = false;
							message = "上传文件不能为空!";
							break;
						}

						/* 检查文件后缀 */
						if (isPic && !ImageUtils.chkImgExt(ext)) {//// 图片格式校验
							success = false;
							message = "图片格式不正确(必须为.jpg/.jpeg/.png/.gif/.bmp格式文件)!";
							break;
						} else if (!isPic && !ImageUtils.chkFileExt(ext)) {// 文件校验
							success = false;
							message = "文件格式必须为zip或rar!";
							break;
						}

						/* 检查文件大小 */
						if (imageSize > UploadConstant.UPLOAD_MAX_SIZE) {
							success = false;
							message = "上传文件的大小不能超过500MB!";
							break;
						}

						String newFileName = getNewFileName(fileNameLong, isPic, ext);
						String filepath = imagepath + newFileName;

						InputStream in = item.getInputStream();
						upload(map, newFileName, filepath, imageType, fileNameLong, isPic,
								ext, imagepath, in);
						in.close();
						message = "上传文件成功";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "上传文件失败!";
			success = false;
		}

		map.put("success", success);
		map.put("message", message);
		return map;
	}

	/**
	 * 调用远程上传文件操作
	 * @param newFileName
	 * @param filepath
	 * @param imageType
	 * @param fileNameLong
	 * @param isPic
	 * @param ext
	 * @param imagepath
	 * @param in
	 * @throws Exception
	 */
	public static void upload(Map<String,Object> map, String newFileName, String filepath, String imageType,
			String fileNameLong, boolean isPic, String ext, String imagepath, InputStream in)
			throws Exception {
		//创建HessianProxyFactory实例
        HessianProxyFactory factory = new HessianProxyFactory();
        //获得Hessian服务的远程引用
        FileUploadService uploader = (FileUploadService) factory.create(FileUploadService.class, UploadConstant.UPLOAD_SERVICE);
        //调用远程服务上传文件。
        uploader.upload(UploadConstant.UPL_DIR,imagepath,newFileName, in);

        map.put("fileName", newFileName);
        map.put("url", UploadConstant.URL);
        map.put("logoUrl", filepath);

		// 供应商上传款式图片进行压缩
		if (UploadConstant.IMAGE_TYPE_STYLE.equals(imageType)) {

			newFileName = getNewFileName(fileNameLong, isPic, ext);
			String newFilepath = imagepath + newFileName;// 压缩后的文件
			String[] pixelThan = UploadConstant.PIXEL_THAN.split("x");
			Integer width = Integer.valueOf(pixelThan[0]);
			Integer hight = Integer.valueOf(pixelThan[1]);

			uploader.thumbnails(UploadConstant.UPL_DIR, filepath,newFilepath, width, hight);

			map.put("compressUrl", newFilepath);
		}
	}
	/**
     * @param isPic
     * @Description  获取新的文件名  命名格式：yyyyMMddHHmmssSSS_三位随机数
	 * @param fileExt 后缀名
	 * @return
	 */
	public static String getNewFileName(String fileName, boolean isPic,String fileExt){
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmssSSS");
		Integer random = new Random().nextInt(899)+100;
		String fullPath = "";
		if(isPic){
			fullPath = df.format(new Date())+random + "." + fileExt;
		}else{
			fullPath = df.format(new Date())+random + "_" + fileName;
		}
		return fullPath;
	}

	public static final String ALIYUN_OSS_PREFIX = "https://img.dingzhilian.com/";

	/**
	 * 上传图片到阿里云
	 */
	public static String uploadImg(HttpServletRequest request) {
		String imgKey = ALiYunOSSConstant.BUSINESS_IMG_CENTRE;
		List<String> fileList = new ArrayList<>();
		OSS ossClient = null;
		InputStream in = null;
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				if (item.isFormField())
					continue;
				else {
					if (!EmptyUtils.isEmpty(item.getName())) {

						/* 获取文件上传路径名称 */
						String fileNameLong = item.getName();
						/* 获取文件扩展名 */
						String ext = fileNameLong.substring(fileNameLong.lastIndexOf(".") + 1);
						long imageSize = item.getSize();
						if (imageSize == 0) {
							//throw new CommonsException("请上传文件");
							return "请上传文件";
						}
						if (imageSize > 5242880) {
							//throw new CommonsException("图片大小不能超过5MB");
							return "图片大小不能超过5MB";
						}
						//文件名称
						String newFileName = UploadUtil.getNewFileName(fileNameLong, true, ext);
						in = item.getInputStream();
						ossClient = new OSSClientBuilder().build(ALiYunOSSConstant.OSS_ENDPOINT, ALiYunOSSConstant.OSS_ACCESS_KEY_ID, ALiYunOSSConstant.OSS_ACCESS_KEY_SECRET);
						// 创建PutObjectRequest对象。
						PutObjectRequest putObjectRequest = new PutObjectRequest(ALiYunOSSConstant.BUCKET_NAME, imgKey + newFileName, in);

						// 上传
						ossClient.putObject(putObjectRequest);
						fileList.add(ALIYUN_OSS_PREFIX + imgKey + newFileName);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(EmptyUtils.isNotEmpty(in)){
					in.close();
				}
				if(EmptyUtils.isNotEmpty(ossClient)){
					// 关闭OSSClient。
					ossClient.shutdown();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return String.join(",",fileList);
	}


	/**
	 * @Description:二维码图片上传
	 * @param in
	 * @author: liuguanjun
	 * @time:2021年09月06日 下午16:24:43
	 */
	public static String uploadPic(InputStream in) throws Exception{
		String ext = "png";
		boolean isPic = true;
		String newFileName = getNewFileName("", isPic, ext);
		//图片上传阿里云的方式
		String imgKey = ALiYunOSSConstant.WELFARE_IMG_CENTRE;
		OSS ossClient = new OSSClientBuilder().build(ALiYunOSSConstant.OSS_ENDPOINT, ALiYunOSSConstant.OSS_ACCESS_KEY_ID,ALiYunOSSConstant.OSS_ACCESS_KEY_SECRET);
		// 创建PutObjectRequest对象。
		PutObjectRequest putObjectRequest = new PutObjectRequest(ALiYunOSSConstant.BUCKET_NAME,imgKey+newFileName , in);
		// 上传
		ossClient.putObject(putObjectRequest);
		return ImageUtils.setImageSrc(imgKey + newFileName);
	}

	/**
	 * 上传视频到阿里云
	 */
	public static String uploadVideo(HttpServletRequest request) {
		String imgKey = ALiYunOSSConstant.BUSINESS_IMG_CENTRE;
		String fileName = "";
		OSS ossClient = null;
		InputStream in = null;
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				if (item.isFormField())
					continue;
				else {
					if (!EmptyUtils.isEmpty(item.getName())) {

						/* 获取文件上传路径名称 */
						String fileNameLong = item.getName();
						/* 获取文件扩展名 */
						String ext = fileNameLong.substring(fileNameLong.lastIndexOf(".") + 1);
						long videoSize = item.getSize();
						if (videoSize == 0) {
							//throw new CommonsException("请上传文件");
							return "请上传文件";
						}
						//文件名称
						String newFileName = UploadUtil.getNewFileName(fileNameLong, true, ext);
						in = item.getInputStream();
						ossClient = new OSSClientBuilder().build(ALiYunOSSConstant.OSS_ENDPOINT, ALiYunOSSConstant.OSS_ACCESS_KEY_ID, ALiYunOSSConstant.OSS_ACCESS_KEY_SECRET);
						// 创建PutObjectRequest对象。
						PutObjectRequest putObjectRequest = new PutObjectRequest(ALiYunOSSConstant.BUCKET_NAME, imgKey + newFileName, in);

						// 上传
						ossClient.putObject(putObjectRequest);
						fileName = imgKey + newFileName;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				// 关闭OSSClient。
				ossClient.shutdown();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ALIYUN_OSS_PREFIX + fileName;
	}

}
